#include<iostream>
#include<mysql/mysql.h>
#include<jsoncpp/json/json.h>
/*
    用来获取博客列表的cgi程序
*/

using namespace std;
#include"common.hpp"
#include"../log.hpp"
#define TOKEN_ERR -1;
#define QUERY_STRING_ERR -2
#define VERIFY_TOKEN_ERR -3
#define SQL_CON_ERR -4
#define QUERY_ERR -5
#define RES_ERR -6
extern Log lg;
bool getQueryString(std::string &query)
{
    std::string method;
    method = getenv("METHOD");

    if ("GET" != method)
    {
        // 不对其他请求处理
        return false;
    }
    query=getenv("QUERY_STRING");
    return true;

}
int init(string&token,string&query)
{
    if(!getToken(token)){
        cerr<<"DEBUG: gettoken error!!"<<endl;
        return TOKEN_ERR;
    }
  cerr<<"DEBUG: token:"<<token<<endl;

  if(!getQueryString(query))
  {
    cerr<<"DEBUG: getQueryString error!!"<<endl;
    return QUERY_STRING_ERR;
  }
  cerr<<"DEBUG: query_string"<<query<<endl;
    return 0;
}
void pasingString(const string& s,int&p,int&l)
{
    string left,right;
    cutString(s,left,right,"&");
    string page,pvalue;
    cutString(left,page,pvalue,"=");
    string limit,lvalue;
    cutString(right,limit,lvalue,"=");
   p =atoi(pvalue.c_str());
   l =atoi(lvalue.c_str());
}

int mysqlGetBolgsList(const string&token,int limit,Json::Value&data)
{
    stringstream ss;
    string user_id;
    if(!AuthMiddleware::verify_token(token,user_id))
    {
        lg(ERROR,__LINE__,"Verify_token 验证token失败!");

        return VERIFY_TOKEN_ERR;
    }
    //cerr<<"DEBUG:userid=  "<<user_id<<endl;
    
    MYSQL *conn = mysql_init(nullptr);
    if (nullptr == mysql_real_connect(conn, "127.0.0.1", "ldcwd", "123456", "httptest", 3306, nullptr, 0))
    {
      //  std::cerr << " mysql connect error !!" << std::endl;
        lg(ERROR,__LINE__,"mysql_real_connect  连接数据库失败!");

        return SQL_CON_ERR;
    }
   // std::cerr << "sql connect success!! " << std::endl;
    //查询语句
    ss<<"select id,user_id,title ,content,create_at from blogs where user_id="\
    <<user_id<<" order by create_at DESC limit "<<to_string(limit)<<";";
    //cerr<<"DEBUG: BLOGS SQL : "<<ss.str()<<endl;
   if( mysql_query(conn,ss.str().c_str()))
   {
        lg(ERROR,__LINE__,"mysql_query 数据库查询失败!");

    return QUERY_ERR;
   }
   //获取结果集指针
   MYSQL_RES* res= mysql_store_result(conn);
   if(nullptr==res)
   {
        lg(ERROR,__LINE__,"mysql_store_result 结果集获取失败!");

    return RES_ERR;
   }
    //获取行数
    int row=mysql_num_rows(res);
    row=row>limit?limit:row;
    //获取列
    int field=mysql_num_fields(res);
    //遍历结果集
    for(int i=0;i<row;i++)
    {
       MYSQL_ROW row_content= mysql_fetch_row(res);//获取内容行
            //把每一行内容存在一个结构体里
    Json::Value blog;
       blog["blogid"] =row_content[0];
        blog["userid"]=row_content[1];
        blog["title"]=row_content[2];
        string content=row_content[3];
        if(content.size()>100)
        {
            content=content.substr(99);
        }
        blog["content"]=content;
        blog["create"]=row_content[4];
        data.append(blog);
    }

mysql_free_result(res);
mysql_close(conn);
return 0;
}
// 通过返回码code构建一个可返回的string
std::string buildString(const int &code,Json::Value&data)
{
     std::string ret;
    // 返回json格式的blogs
    Json::Value v; // 万能对象结构体

    switch (code)
    {
    case 0:
        // 把对应的键值对写入 万能对象结构体
        v["success"] = true;
        v["message"] = "获取成功!!";
        v["data"]=data;
        break;
    
    case QUERY_ERR:
        v["success"] = false;
        v["message"] = "查询失败!";
        break;
    case QUERY_STRING_ERR:
        v["success"] = false;
        v["message"] = "url参数错误!!";
        break;
    case VERIFY_TOKEN_ERR:
        v["success"] = false;
        v["message"] = "授权验证失败";
        break;
    case SQL_CON_ERR:
        v["success"] = false;
        v["message"] = "连接错误!!!";
        break;
    case RES_ERR:
        v["success"] = false;
        v["message"] = "结果集错误!!!";
        break;
    }
    // 序列化JSON得到一个串
    Json::StyledWriter w;
    ret = w.write(v);
    return ret;
}
int main()
{
    lg.Enable(3);
 Json::Value array(Json::arrayValue);//json数组

    string token;
  string query_string;
    if(init(token,query_string)!=0)
    {   
        lg(ERROR,__LINE__,"Get Blogs_list 初始化token,参数失败!");
        return -1;
    }
    //解析参数获取page、limit
    int need_pagval,need_limval;
    pasingString(query_string,need_pagval,need_limval);

//获取博客列表
  int n=  mysqlGetBolgsList(token,need_limval,array);
string ret=buildString(n,array);
cout<<ret;
// cerr<<"DEBUG-----------------1"<<endl;
//    string token= AuthMiddleware::generate_random_token("1234");
// cerr<<"DEBUG-------:<<token<<----------2"<<endl;


//    string userid;
//    if(AuthMiddleware::verify_token(token,userid))
//    {
//     cerr<<userid<<endl;
//    }
// cerr<<"DEBUG-----------------3"<<endl;

    return 0;
}